package bb.lanxing.activity.login

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.TranslateAnimation
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.activity.agreement.AgreementActivity
import bb.lanxing.activity.interfaces.ILoginPresenter
import bb.lanxing.activity.interfaces.ILoginView
import bb.lanxing.common.config.Constants
import bb.lanxing.common.config.UmengEventConst
import bb.lanxing.databinding.ActivityLoginAccountBinding
import bb.lanxing.lib.devices.sprint.entity.SettingSupports
import bb.lanxing.manager.SharedManager
import bb.lanxing.model.bean.LoginModel
import bb.lanxing.model.database.City
import bb.lanxing.model.database.Province
import bb.lanxing.model.database.User
import bb.lanxing.model.event.MyProfileEvent
import bb.lanxing.model.event.UserSignoutEvent
import bb.lanxing.mvp.presetner.ClubPresenter
import bb.lanxing.mvp.presetner.LoginPresenterImpl
import bb.lanxing.util.BusProvider
import bb.lanxing.util.InputHelper
import bb.lanxing.util.InstallerUtil
import com.tencent.tauth.Tencent
import com.umeng.analytics.MobclickAgent
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import org.apache.commons.cli.HelpFormatter
import org.json.JSONObject
import org.litepal.LitePal.where

class AccountLoginActivity : AgreementActivity(), ILoginView {
    private lateinit var accountView: EditText
    private lateinit var deleteNum: ImageView
    private lateinit var deletePass: ImageView
    private lateinit var loginBinding: ActivityLoginAccountBinding
    private var loginPresenter: ILoginPresenter? = null
    private var openObject: JSONObject? = null
    private lateinit var passwordView: EditText

    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        loginBinding = ActivityLoginAccountBinding.inflate(layoutInflater)
        setContentView(loginBinding.root)
        initView()
        initLastLoginStyle()
        initClick()
        loginBinding.rootView.setOnKeyboardStateChangeListener { z: Boolean ->
            if (z) {
                dismissLogo()
                loginBinding.thirtPartyView.visibility = View.GONE
                return@setOnKeyboardStateChangeListener
            }
            showLogoAnimation()
            loginBinding.thirtPartyView.visibility = View.VISIBLE
        }
    }

    fun initView() {
        loginPresenter = LoginPresenterImpl(this)
        accountView = loginBinding.root.findViewById(R.id.accountView)
        passwordView = loginBinding.root.findViewById(R.id.passwordView)
        deletePass = loginBinding.root.findViewById(R.id.deletePass)
        deleteNum = loginBinding.root.findViewById(R.id.deleteNum)

        loginBinding.cbLoginUserAgreement.setOnCheckedChangeListener { compoundButton: CompoundButton?, z: Boolean -> checkEnable() }
        loginBinding.tvLoginUserAgreement.text =
            getSpannableStringBuilder(this@AccountLoginActivity)
        loginBinding.tvLoginUserAgreement.movementMethod = LinkMovementMethod.getInstance()
        loginBinding.loginBtn.isEnabled = false
        setTitle(R.string.mine_login_label_phone_login)
        setupActionBar(true)
        accountView.setOnFocusChangeListener { _, z: Boolean ->
            deleteNum.setVisibility(
                if ((!z || accountView.getText().isEmpty())) View.GONE else View.VISIBLE
            )
        }
        accountView.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {
            }

            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                checkEnable()
            }
        })
        passwordView.setOnFocusChangeListener { view: View?, z: Boolean ->
            deletePass.setVisibility(
                if ((!z || passwordView.getText().isEmpty())) View.GONE else View.VISIBLE
            )
        }
        passwordView.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {
            }

            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                checkEnable()
            }
        })

        deletePass.setOnClickListener { _ ->
            passwordView.setText("")
            deletePass.setVisibility(View.GONE)
        }

        deleteNum.setOnClickListener { _ ->
            accountView.setText("")
            deleteNum.setVisibility(View.GONE)
        }
    }

    fun checkEnable() {
        val length = accountView.text.length
        val length2 = passwordView.text.length
        loginBinding.loginBtn.isEnabled =
            length > 0 && length2 > 0 && loginBinding.cbLoginUserAgreement.isChecked
        deleteNum.visibility = if (length > 0) View.VISIBLE else View.GONE
        deletePass.visibility = if (length2 <= 0) View.GONE else View.VISIBLE
    }

    private fun initLastLoginStyle() {
        val lastLoginStyle = SharedManager.getInstance().lastLoginStyle
        if (lastLoginStyle == -1) {
            loginBinding.weiboLogin.visibility = View.GONE
            loginBinding.wechatLogin.visibility = View.GONE
            loginBinding.qqLogin.visibility = View.GONE
            if (!TextUtils.isEmpty(SharedManager.getInstance().email)) {
                accountView.setText(SharedManager.getInstance().email)
            }
            if (TextUtils.isEmpty(SharedManager.getInstance().userPhone)) {
                return
            }
            accountView.setText(SharedManager.getInstance().userPhone)
        } else if (lastLoginStyle == 0) {
            loginBinding.qqLogin.visibility = View.VISIBLE
            loginBinding.wechatLogin.visibility = View.GONE
            loginBinding.weiboLogin.visibility = View.GONE
        } else if (lastLoginStyle == 1) {
            loginBinding.wechatLogin.visibility = View.VISIBLE
            loginBinding.qqLogin.visibility = View.GONE
            loginBinding.weiboLogin.visibility = View.GONE
        } else if (lastLoginStyle != 2) {
        } else {
            loginBinding.weiboLogin.visibility = View.VISIBLE
            loginBinding.wechatLogin.visibility = View.GONE
            loginBinding.qqLogin.visibility = View.GONE
        }
    }

    fun dismissLogo() {
        val translateAnimation =
            TranslateAnimation(0.0f, 0.0f, 0.0f, -loginBinding.logoView.height.toFloat())
        translateAnimation.duration = 500L
        translateAnimation.fillAfter = false
        loginBinding.logoView.startAnimation(translateAnimation)
        val alphaAnimation = AlphaAnimation(1.0f, 0.0f)
        alphaAnimation.duration = 500L
        alphaAnimation.fillAfter = false
        loginBinding.logoImage.startAnimation(alphaAnimation)
        loginBinding.logoView.visibility = View.GONE
    }

    fun showLogoAnimation() {
        val translateAnimation =
            TranslateAnimation(0.0f, 0.0f, -loginBinding.logoView.height.toFloat(), 0.0f)
        translateAnimation.duration = 500L
        translateAnimation.fillAfter = false
        loginBinding.logoView.startAnimation(translateAnimation)
        val alphaAnimation = AlphaAnimation(0.0f, 1.0f)
        alphaAnimation.duration = 500L
        alphaAnimation.fillAfter = false
        loginBinding.logoImage.startAnimation(alphaAnimation)
        loginBinding.logoView.visibility = View.VISIBLE
    }

    private fun initClick() {
    }

    private fun umDoOauthVerify(share_media: SHARE_MEDIA) {
        if (share_media != SHARE_MEDIA.SINA) {
            showLoadingDialog(getString(R.string.dialog_loading), true)
        }
        if (Province.getCount() <= 0) {
            Province.importDatas()
            City.importDatas()
        }
        openObject = JSONObject()
        Tencent.setIsPermissionGranted(true)
        UMShareAPI.get(this).getPlatformInfo(this, share_media, object : UMAuthListener {
            override fun onStart(share_media2: SHARE_MEDIA) {
                Log.i("umDoOauthVerify", "onStart $share_media2")
            }

            override fun onComplete(share_media2: SHARE_MEDIA, i: Int, map: Map<String, String>) {
                val str: String?
                Log.d("umDoOauthVerify", "doOauthVerify map == $map")
                if (map != null && (share_media2 == SHARE_MEDIA.WEIXIN || !TextUtils.isEmpty(
                        map["uid"]
                    ))
                ) {
                    try {
                        var str2: String? = null
                        var i2 = 0
                        if (share_media == SHARE_MEDIA.QQ) {
                            str2 = map["access_token"]
                            str = map["openid"]
                        } else if (share_media == SHARE_MEDIA.WEIXIN) {
                            i2 = 1
                            str2 = map["access_token"]
                            str = map["openid"]
                        } else if (share_media == SHARE_MEDIA.SINA) {
                            i2 = 2
                            var str3 = map["access_key"]
                            if (TextUtils.isEmpty(str3)) {
                                str3 = map["access_token"]
                            }
                            str2 = str3
                            str = map["uid"]
                        } else {
                            str = null
                        }
                        openObject!!.put("ltype", i2)
                        openObject!!.put("access_token", str2)
                        openObject!!.put(
                            com.tencent.connect.common.Constants.JumpUrlConstants.URL_KEY_OPENID,
                            str
                        )
                        getPlatformInfo(share_media)
                        return
                    } catch (e: Exception) {
                        App.getContext().showMessage(R.string.mine_profile_toast_3rd_parse_failed)
                        e.printStackTrace()
                        dismissLoadingDialog()
                        return
                    }
                }
                App.getContext().showMessage(R.string.mine_profile_toast_3rd_auth_failed)
                dismissLoadingDialog()
            }

            override fun onError(share_media2: SHARE_MEDIA, i: Int, th: Throwable) {
                Log.d("umDoOauthVerify", "umDoOauthVerify onError $share_media2 , $th")
                App.getContext().showMessage(R.string.mine_profile_toast_3rd_auth_error)
                dismissLoadingDialog()
            }

            override fun onCancel(share_media2: SHARE_MEDIA, i: Int) {
                dismissLoadingDialog()
            }
        })
    }

    private fun getPlatformInfo(share_media: SHARE_MEDIA) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, object : UMAuthListener {
            override fun onStart(share_media2: SHARE_MEDIA) {
                Log.i("getPlatformInfo", "onStart $share_media2")
            }

            override fun onComplete(share_media2: SHARE_MEDIA, i: Int, map: Map<String, String>) {
                val str: String?
                val str2: String?
                val i2: Boolean
                Log.d(
                    "getPlatformInfo", "status = " + i + HelpFormatter.DEFAULT_LONG_OPT_PREFIX + map
                )
                try {
                    var i3 = 1
                    var str5: String? = null
                    if (share_media == SHARE_MEDIA.QQ) {
                        str = map["screen_name"]
                        str2 = map["profile_image_url"]
                        i2 = "男" == map[SettingSupports.SUPPORT_ITEM_GENDER]
                    } else if (share_media == SHARE_MEDIA.WEIXIN) {
                        str5 = map["unionid"]
                        str = map["screen_name"]
                        str2 = map["profile_image_url"]
                        i2 = "男" == map[SettingSupports.SUPPORT_ITEM_GENDER]
                    } else if (share_media == SHARE_MEDIA.SINA) {
                        str = map["screen_name"]
                        str2 = map["profile_image_url"]
                        i3 = map["city"]?.toInt() ?: 0
                        i2 = "男" == map[SettingSupports.SUPPORT_ITEM_GENDER]
                    } else {
                        str = null
                        str2 = null
                        i2 = false
                    }
                    if (!TextUtils.isEmpty(str5)) {
                        openObject!!.put("union_id", str5)
                    }
                    openObject!!.put("avatar", str2)
                    openObject!!.put("nick_name", str)
                    val i4 = 0
                    val jSONObject = openObject
                    jSONObject!!.put("city_id", i3)
                    openObject!!.put(SettingSupports.SUPPORT_ITEM_GENDER, i2)
                    loginPresenter!!.loginByThirdParty(share_media, openObject)
                    return
                } catch (e: Exception) {
                    App.getContext().showMessage(R.string.mine_profile_toast_3rd_request_failed)
                    e.printStackTrace()
                    dismissLoadingDialog()
                    return
                }
                App.getContext().showMessage(R.string.mine_profile_toast_3rd_request_failed)
                dismissLoadingDialog()
            }

            override fun onError(share_media2: SHARE_MEDIA, i: Int, th: Throwable) {
                Log.e("getPlatformInfo", "onError $share_media2 , $th")
                App.getContext().showMessage(R.string.mine_profile_toast_3rd_auth_error)
                dismissLoadingDialog()
            }

            override fun onCancel(share_media2: SHARE_MEDIA, i: Int) {
                Log.i("getPlatformInfo", "onCancel $share_media2")
                dismissLoadingDialog()
            }
        })
    }

    override fun onLoginResult(user: User) {
        runOnUiThread {
            loginBinding.loginBtn.isEnabled = true
            loginSuccess(user)
            finish()
        }
    }

    override fun onLoginByThirdPartyResult(user: User) {
        if (!TextUtils.isEmpty(user.phone)) {
            loginSuccess(user)
            finish()
        } else {
            user.save()
            val intent = Intent(this, PhoneBindActivity::class.java)
            intent.putExtra("type", Constants.AUTHCODE_TYPE_BICI_FIND_PASSWORD)
            intent.putExtra("user_id", user.uid)
            startActivityForResult(intent, REQUEST_CODE_BIND_PHONE)
        }
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, intent)
        if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_VERIFICATION || REQUEST_CODE_BIND_PHONE == requestCode)) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        loginPresenter!!.destroy()
    }

    fun loginBtnClick(view: View) {
        val account = accountView.text.toString().trim { it <= ' ' }
        val pwd = passwordView.text.toString().trim { it <= ' ' }
        loginBinding.loginBtn.isEnabled = false
        loginPresenter!!.login(account, pwd)
        InputHelper.hideSoftInput(accountView)
    }

    fun registerBtnClick(view: View) {
        MobclickAgent.onEventValue(
            this@AccountLoginActivity, UmengEventConst.ACCOUNT_REGISTER, null, 1
        )
        startActivity(Intent(this@AccountLoginActivity, PhoneRegisterActivity::class.java))
    }

    fun qqLoginClick(view: View) {
        if (!loginBinding.cbLoginUserAgreement.isChecked) {
            App.getContext().showMessage(R.string.mine_login_user_agreement)
        } else if (InstallerUtil.isAppInstalled(
                this@AccountLoginActivity, InstallerUtil.APP_QQ
            )
        ) {
            Tencent.setIsPermissionGranted(true)
            umDoOauthVerify(SHARE_MEDIA.QQ)
        } else {
            App.getContext().showMessage(R.string.mine_login_third_party_no_qq)
        }
    }

    fun weixinLoginClick(view: View) {
        if (!loginBinding.cbLoginUserAgreement.isChecked) {
            App.getContext().showMessage(R.string.mine_login_user_agreement)
        } else if (InstallerUtil.isAppInstalled(
                this@AccountLoginActivity, InstallerUtil.APP_WECHAT
            )
        ) {
            umDoOauthVerify(SHARE_MEDIA.WEIXIN)
        } else {
            App.getContext().showMessage(R.string.mine_login_third_party_no_weixin)
        }
    }

    fun weiboLoginClick(view: View) {
        if (!loginBinding.cbLoginUserAgreement.isChecked) {
            App.getContext().showMessage(R.string.mine_login_user_agreement)
        } else if (InstallerUtil.isAppInstalled(
                this@AccountLoginActivity, InstallerUtil.APP_SINA
            )
        ) {
            umDoOauthVerify(SHARE_MEDIA.SINA)
        } else {
            App.getContext().showMessage(R.string.mine_login_third_party_no_weibo)
        }
    }

    fun messageLoginClick(view: View) {
        val intent = Intent(this@AccountLoginActivity, VerificationLoginActivity::class.java)
        intent.putExtra("name", accountView.text.toString().trim { it <= ' ' })
        startActivityForResult(intent, REQUEST_CODE_VERIFICATION)
    }

    fun forgetPassClick(view: View) {
        MobclickAgent.onEventValue(
            this@AccountLoginActivity, UmengEventConst.ACCOUNT_FIND_PASSWORD, null, 1
        )
        val intent = Intent(this@AccountLoginActivity, PhoneBindActivity::class.java)
        intent.putExtra("type", Constants.AUTHCODE_TYPE_FORGET_PASSWORD)
        startActivity(intent)
    }

    companion object {
        private const val REQUEST_CODE_VERIFICATION = 101
        private const val REQUEST_CODE_BIND_PHONE = 102

        @JvmStatic
        fun launchLoginActivity(context: Context, i: Int) {
            val intent = Intent(context, AccountLoginActivity::class.java)
            if (i != 0) {
                intent.setFlags(i)
            }
            context.startActivity(intent)
        }

        fun loginSuccess(user: User) {
            // TODO: 12/27/2023 暂时注释网络相关的
            SharedManager.getInstance().isSignoutFlag = true
            BusProvider.getInstance().post(UserSignoutEvent(user.uid.toLong()))
            val tempUser = where("phone=?", user.phone).findFirst(
                User::class.java
            )
            if (tempUser == null) {
                user.save()
                App.getContext().signinUser = user
                SharedManager.getInstance().userPhone = user.phone
            } else {
                tempUser.uid = user.uid
                tempUser.name = user.phone
                tempUser.save()
                App.getContext().signinUser = tempUser
                SharedManager.getInstance().userPhone = tempUser.phone
            }

            SharedManager.getInstance().setUserAgreement(user.uid, true)
            SharedManager.getInstance().userId = user.uid
            App.getContext().showMessage(R.string.mine_login_toast_login_successful)
            App.getContext().uploadDeviceToken()
            ClubPresenter.postClubEvent(15, 0L, null)
            BusProvider.getInstance().post(MyProfileEvent(1))
            BusProvider.getInstance().post(MyProfileEvent(4))
            BusProvider.getInstance().post(LoginModel())
        }
    }
}